/**********************************
 * @Author: Ronnie Zhang
 * @LastEditor: Ronnie Zhang
 * @LastEditTime: 2023/12/05 21:22:43
 * @Email: zclzone@outlook.com
 * Copyright © 2023 Ronnie Zhang(大脸怪) | https://isme.top
 **********************************/

import { cloneDeep } from 'lodash-es'

export function useForm(initFormData = {}) {
  const formRef = ref(null)
  const formModel = ref(cloneDeep(initFormData))
  const rules = {
    required: {
      required: true,
      message: '此为必填项',
      trigger: ['change'],
    },
  }
  const validation = (callback) => {
    // 如果提供了callback，则进行验证
    return new Promise((resolve, reject) => {
      if (!formRef.value) {
        resolve()
        return
      }

      // 使用Promise方式处理验证，只在用户提交时触发
      formRef.value.validate((errors) => {
        if (errors && Object.keys(errors).length > 0) {
          console.log('表单验证错误:', errors)
          if (typeof callback === 'function') {
            callback(errors)
          }
          reject(new Error('验证失败'))
        }
        else {
          if (typeof callback === 'function') {
            callback(null)
          }
          resolve()
        }
      })
    })
  }
  return [formRef, formModel, validation, rules]
}
